package com.other.src.main.java.com.kuang.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class SpinlockDemo {

//    private String LockA;
//    private String LockB;
//
//    public SpinlockDemo(String lockA, String lockB) {
//        LockA = lockA;
//        LockB = lockB;
//    }

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {

        Thread thread = Thread.currentThread();

        System.out.println(Thread.currentThread().getName()+" ==> myLock");

        while (!atomicReference.compareAndSet(null,thread)){

        }

    }
    public void myUnLock() {

        Thread thread = Thread.currentThread();

        System.out.println(Thread.currentThread().getName()+" ==> myUnLock");

         atomicReference.compareAndSet(thread,null);

}
}
class TestSpinlock{
    public static void main(String[] args) throws InterruptedException {
        SpinlockDemo lock = new SpinlockDemo();

        new Thread(()->{


            lock.myLock();

            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.myUnLock();
            }
        },"T1").start();
        TimeUnit.SECONDS.sleep(2);
        new Thread(()->{
            lock.myLock();

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.myUnLock();
            }
        },"T2").start();
    }
}